package com.easy.work;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.base.syslib.Logs;
import com.base.syslib.util.MessageTools;
import com.easy.work.app.AppSession;
import com.easy.work.app.BaseActivity;
import com.easy.work.app.BaseFragment;
import com.easy.work.app.CommonValue;
import com.easy.work.bean.MsgEvent;
import com.easy.work.db.DataProvider;
import com.easy.work.db.MessageBean;
import com.easy.work.fragment.MainFragment;
import com.easy.work.fragment.MallFragment;
import com.easy.work.fragment.MeFragment;
import com.easy.work.fragment.MessageFragment;
import com.easy.work.function.SettingActivity;
import com.easy.work.function.SplashActivity;
import com.easy.work.http.BaseResponse;
import com.easy.work.http.HttpClient;
import com.easy.work.http.request.CheckResumeRequest;
import com.easy.work.http.request.GetResumeInfoRequest;
import com.easy.work.http.request.ReceiveAliasRequest;
import com.easy.work.http.response.CheckResumeResponse;
import com.easy.work.http.response.ResumeInfoResponse;
import com.easy.work.utils.StringUtil;
import com.easy.work.utils.UpdateManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    @BindView(R.id.tv_msg)
    TextView tvMsg;
    @BindView(R.id.rb_main)
    RadioButton rbMain;
    @BindView(R.id.rb_message)
    RadioButton rbMessage;
    @BindView(R.id.rb_mall)
    RadioButton getRbMain;
    @BindView(R.id.rb_me)
    RadioButton rbMe;
    @BindView(R.id.main_bottom)
    RadioGroup mainBottom;
    @BindView(R.id.fragment_container)
    RelativeLayout fragmentContainer;
    @BindView(R.id.mainLayout)
    RelativeLayout mainLayout;
    @BindView(R.id.dl)
    LinearLayout dl;
    private MainFragment mainFragment;
    private MallFragment mallFragment;
    private MessageFragment messageFragment;
    private MeFragment meFragment;
    private BaseFragment[] fragments;

//    /**
//     * 定位
//     */
//    private LocationService locationService;

    private int index;
    // 当前fragment的index
    private int currentTabIndex = 0;

    /**
     * 个人信息
     */
    public ResumeInfoResponse resumeInfoResponse;

    private boolean isActive;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initDate();
        initPush();
        initFragment();
//        initLocation();
    }

    private void initDate() {
        UpdateManager.getUpdateManager().checkAppUpdate(MainActivity.this, false, false);
        getResumeInfo();
        getCheck();
    }

    /**
     * 是否完善简历
     */
    private void getCheck() {
        CheckResumeRequest request = new CheckResumeRequest();
        request.userId = AppSession.getInstance().getUserId();
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                CheckResumeResponse response1 = (CheckResumeResponse) response;
                if (response1.status.equals("0")) {
                    AppSession.getInstance().setResumePerfect(false);
                } else if (response1.status.equals("1")) {
                    AppSession.getInstance().setResumePerfect(true);
                } else {
                    AppSession.getInstance().setResumePerfect(false);
                }


            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                MessageTools.showToast(oThis, msg);
            }
        });
    }

    /**
     * 获取简历信息
     */
    private void getResumeInfo() {
        GetResumeInfoRequest request = new GetResumeInfoRequest();
        request.userId = AppSession.getInstance().getUserId();
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                resumeInfoResponse = (ResumeInfoResponse) response;


            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                MessageTools.showToast(oThis, msg);
            }
        });
    }

    public void refresh() {
        getResumeInfo();
    }


//    private void initLocation() {
//        locationService = ((MyApplication) getApplication()).locationService;
//        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
//        locationService.registerListener(mListener);
//        //注册监听
//        int type = getIntent().getIntExtra("from", 0);
//        if (type == 0) {
//            locationService.setLocationOption(locationService.getDefaultLocationClientOption());
//        } else if (type == 1) {
//            locationService.setLocationOption(locationService.getOption());
//        }
//        locationService.start();// 定位SDK
//    }

//    /*****
//     *
//     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
//     *
//     */
//    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
//
//        @Override
//        public void onReceiveLocation(BDLocation location) {
//
//            Logs.e(tag, "定位成功....");
//            // TODO Auto-generated method stub
//            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
//                StringBuffer sb = new StringBuffer(256);
//                sb.append("time : ");
//                /**
//                 * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
//                 * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
//                 */
//                final BDLocation location1 = location;
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
////                        String cityCode = StringUtil.getCityCode(getApplicationContext(), location1.getCity());
//                        AppSession.getInstance().setCityCodeForName(location1.getCity());
////                        AppSession.saveAppSessionData(SPKey.cityCode, code);
//                    }
//                }).start();
//
//                AppSession.getInstance().setLatitude(String.valueOf(location.getLatitude()));
//                AppSession.getInstance().setLontitude(String.valueOf(location.getLongitude()));
//                AppSession.getInstance().setCityName(location.getCity());
//                if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
//                    sb.append("\nspeed : ");
//                    sb.append(location.getSpeed());// 速度 单位：km/h
//                    sb.append("\nsatellite : ");
//                    sb.append(location.getSatelliteNumber());// 卫星数目
//                    sb.append("\nheight : ");
//                    sb.append(location.getAltitude());// 海拔高度 单位：米
//                    sb.append("\ngps status : ");
//                    sb.append(location.getGpsAccuracyStatus());// *****gps质量判断*****
//                    sb.append("\ndescribe : ");
//                    sb.append("gps定位成功");
//                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
//                    // 运营商信息
//                    if (location.hasAltitude()) {// *****如果有海拔高度*****
//                        sb.append("\nheight : ");
//                        sb.append(location.getAltitude());// 单位：米
//                    }
//                    sb.append("\noperationers : ");// 运营商信息
//                    sb.append(location.getOperators());
//                    sb.append("\ndescribe : ");
//                    sb.append("网络定位成功");
//                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
//                    sb.append("\ndescribe : ");
//                    sb.append("离线定位成功，离线定位结果也是有效的");
//                } else if (location.getLocType() == BDLocation.TypeServerError) {
//                    sb.append("\ndescribe : ");
//                    sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
//                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
//                    sb.append("\ndescribe : ");
//                    sb.append("网络不同导致定位失败，请检查网络是否通畅");
//                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
//                    sb.append("\ndescribe : ");
//                    sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
//                }
//                Logs.e(tag, sb.toString());
////                logMsg(sb.toString());
//            }
//
//            locationService.stop();
//        }
//
//    };

    /**
     * 初始化推送
     */
    void initPush() {
        JPushInterface.setDebugMode(CommonValue.DEBUG);
        JPushInterface.init(getApplicationContext());
        String registrationID = JPushInterface.getRegistrationID(getApplicationContext());
        JPushInterface.setAlias(getApplicationContext(), 0, registrationID);

        if (StringUtil.isEmpty(registrationID)) {
            Logs.e(tag, "registrationID=null");
        } else {
            Logs.e(tag, "registrationID=" + registrationID);
        }
        ReceiveAliasRequest request = new ReceiveAliasRequest();
        request.alias = registrationID;
        request.userId = AppSession.getInstance().getUserId();
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                Logs.e(tag, "同步推送ID到后台");
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                Logs.e(tag, "同步推送ID到后台失败  msg = " + msg);
            }
        });
    }

    private void initFragment() {
        mainFragment = new MainFragment();
        messageFragment = new MessageFragment();
        mallFragment = new MallFragment();
        meFragment = new MeFragment();
        fragments = new BaseFragment[]{mainFragment, messageFragment, mallFragment, meFragment};
//

        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, mainFragment)
                .hide(mainFragment)
                .add(R.id.fragment_container, messageFragment)
                .hide(messageFragment)
                .add(R.id.fragment_container, mallFragment)
                .hide(mallFragment)
                .add(R.id.fragment_container, meFragment)
                .hide(meFragment)
                .show(mainFragment).commit();
        mainBottom.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId) {
            case R.id.rb_main:
                index = 0;
                break;
            case R.id.rb_message:
                index = 1;
                break;
            case R.id.rb_mall:
                index = 2;
                break;
            case R.id.rb_me:
                index = 3;
                break;
        }
        if (currentTabIndex != index) {

            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            trx.hide(fragments[currentTabIndex]);
            if (!fragments[index].isAdded()) {
                trx.add(R.id.fragment_container, fragments[index]);
            }
            trx.show(fragments[index]).commit();
        }
        currentTabIndex = index;
    }

    /**
     * 退出客户的标志位
     */
    private int repeatCount = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (repeatCount == 0) {
                repeatCount++;
                MessageTools.showToast(oThis, "再按一次退出程序");
                backHandler.sendEmptyMessageDelayed(0, 2000L);
                return true;
            } else {
                Intent intent = new Intent(this, SplashActivity.class);
                intent.putExtra(CommonValue.isExit, true);
                startActivity(intent);
                finish();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 记录退出按下次数
     * 超过时间重置为0
     */
    private Handler backHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            repeatCount = 0;
        }
    };

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Logs.e("Test", "onResume");
        isActive = true;
        refreshMsgCount();
    }

    @Override
    protected void onPause() {
        super.onPause();
        isActive = false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(MsgEvent event) {
        Logs.e("Test", "onMsgEvent-isActive:" + isActive);
        if (isActive) {
            refreshMsgCount();
        }
    }

    private void refreshMsgCount() {
        List<MessageBean> list = DataProvider.getUnreadMsgList(this);
        if (list == null || list.isEmpty()) {
            if (tvMsg.getVisibility() != View.GONE) {
                tvMsg.setVisibility(View.GONE);
            }
        } else {
            if (tvMsg.getVisibility() != View.VISIBLE) {
                tvMsg.setVisibility(View.VISIBLE);
            }
            tvMsg.setText(String.valueOf(list.size()));
        }
        messageFragment.refresh();
    }
}
